package com.yixun.qfbao.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.dao.ApiLogDao;
import com.yixun.qfbao.model.dto.ApiLogDto;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;


/**
 * http请求
 * 
 * @author jzliu
 */
@Component
public class HttpApi {
	private static Logger logger= LoggerFactory.getLogger(HttpApi.class);


	@Autowired
    ApiLogDao apiLogDao;

	public static HttpApi getHttpApi() {
		return httpApi;
	}

	public static void setHttpApi(HttpApi httpApi) {
		HttpApi.httpApi = httpApi;
	}

	private static HttpApi httpApi;

	@PostConstruct //@PostConstruct修饰的方法会在服务器加载Servle的时候运行，并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
	public void init() {
		httpApi = this;
		httpApi.apiLogDao = this.apiLogDao;
	}
	/**
	 * 调用非固定地址
	 * 
	 * @param url 接口url
	 * @param data //json入参
	 * @return json
	 */
	public static String doPostUrl(String url, JSONObject data) {
		String result = null;
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost = null;
		try {
			httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			JSONObject json = new JSONObject();
			json.put("params", data);
			params.add(new BasicNameValuePair("body", json.toString()));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
				}
			}
		} catch (Exception e) {
			logger.error("HttpApi ==> doPostUrl ==> error: {}, ", e);
		}
		return result;
	}
	
	/**
	 * body 未json
	 * 
	 * @param url
	 * @param jsonBody
	 * @return
	 */
	public static byte[] doPostForEntity(String url, String jsonBody) {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost = null;
		try {
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity se = new StringEntity(jsonBody, Charset.forName("UTF-8"));
			se.setContentType("application/json");
			httpPost.setEntity(se);
			HttpResponse response = client.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					return IOUtils.toByteArray(resEntity.getContent());
				}
			}
		} catch (Exception e) {
			logger.error("HttpApi ==> doPost error: {}", e);
		}
		return null;
	}
	
	/**
	 * body 未json
	 * 
	 * @param url
	 * @param jsonBody
	 * @return
	 */
	public static String doPost(String url, String jsonBody) {
		String result = null;
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost = null;
		try {
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity se = new StringEntity(jsonBody, Charset.forName("UTF-8"));
			se.setContentType("application/json");
			httpPost.setEntity(se);
			HttpResponse response = client.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
				}
			}
		} catch (Exception e) {
			logger.error("HttpApi ==> doPost error: {}", e);
		}
		return result;
	}

	/**
	 * body 未json
	 *
	 * @param url
	 * @param jsonBody
	 * @return
	 */
	public static String doPostV10(String url, String jsonBody,String appId,String appKey,String companyUuid,ApiLogDto apiLog) {
		String result = null;
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost = null;

		apiLog.setCreateTime(new Date());
		apiLog.setRequestContent(jsonBody);
		apiLog.setContent(jsonBody);
		apiLog.setUrl(url);
		apiLog.setOtherCompanyId(companyUuid);
		apiLog.setRemark("请求V10: " + companyUuid);
//		httpApi.apiLogDao.create(apiLog);
		try {
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
			httpPost.setHeader("X-AUTH-APP-ID",appId);
			httpPost.setHeader("X-AUTH-KEY",appKey);
			httpPost.setHeader("companyUuid",companyUuid);
			StringEntity se = new StringEntity(jsonBody, Charset.forName("UTF-8"));
			se.setContentType("application/json");
			httpPost.setEntity(se);
			HttpResponse response = client.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
//					apiLog.setRequestId(apiLog.getId());
					apiLog.setId(null);
//					apiLog.setContent(result);
					apiLog.setResponseContent(result);
//					apiLog.setCreateTime(new Date());
//					apiLog.setRemark("V10返回: " + companyUuid);
					httpApi.apiLogDao.create(apiLog);
				}
			}
		} catch (Exception e) {
			logger.error("doPostV10 error: {}", e);
			apiLog.setRemark("V10返回: " + companyUuid);
			apiLog.setResponseContent(e.getMessage());
			httpApi.apiLogDao.create(apiLog);
		}
		return result;
	}


	public static String doPostMarketing(String url,String jsonBody){
		String result = null;
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost = null;
		ApiLogDto apiLog = new ApiLogDto();
		apiLog.setCreateTime(new Date());
		apiLog.setContent(jsonBody);
		apiLog.setUrl(url);
		apiLog.setRemark("请求营销号接口");
		httpApi.apiLogDao.create(apiLog);
		try {
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity se = new StringEntity(jsonBody, Charset.forName("UTF-8"));
			se.setContentType("application/json");
			httpPost.setEntity(se);
			HttpResponse response = client.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
					apiLog.setRequestId(apiLog.getId());
					apiLog.setId(null);
					apiLog.setContent(result);
					apiLog.setCreateTime(new Date());
					apiLog.setRemark("营销号返回");
					httpApi.apiLogDao.create(apiLog);
				}
			}
		} catch (Exception e) {
			logger.error("doPostMarketing error: {}", e);
		}
		return result;
	}
	

	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("sendGet error: {}", e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		String url = "http://qfcc.test.51fxt.com/api/call/standard/v1/sms/getTemplateList";
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token","d97658a4-922a-4010-af09-ff4264c4f54b");
		jsonObject.put("mainAccountCode","Sep");

//		jsonObject.put("subAccountCode", "Seppart");
//		jsonObject.put("templateId", "qfcxb001");
		JSONArray jsonArray = new JSONArray();
//		jsonArray.add("18516541636");
//		jsonObject.put("targets", jsonArray);
//		JSONArray paramsArray = new JSONArray();
//		paramsArray.add("绿城置业");
//		paramsArray.add("王晓");
//		paramsArray.add("李玉");
//		paramsArray.add("手机号错误");
		Map<String,String> map = new HashMap<>();
		map.put("key1","123456");
		map.put("key2","王晓");
		map.put("key3","李玉");
		map.put("key4","手机号错误");
//		jsonObject.put("smsContents","项目：{Param}，客户：{Param}，报备人：{Param}，申诉原因: {Param}，请及时处理");
//		jsonObject.put("templateParas",map);
		System.out.println(jsonObject.toJSONString());
//		String msg = doPostQfSms(url,jsonObject.toJSONString());
//		System.out.println(msg);
	}
}
